layui.config({
    base : "js/"
}).use(['form','layer','jquery','layedit','laydate'],function(){
    var form = layui.form(),
        layer = parent.layer === undefined ? layui.layer : parent.layer,
        laypage = layui.laypage,
        layedit = layui.layedit,
        laydate = layui.laydate,
        $ = layui.jquery;

    var filedir = "information/"; // 对应oss目录
    var isReUploadCoverFlag = false;
    var delImgsArr = [];

    //initInfo(); // 初始化部分信息

    var saveFlag = false;
    // 表单提交:
    form.on("submit(addInformation)",function (data) {
        form.render();
        if(isReUploadCoverFlag && !checkImgUpload()) return false;
        var formData = $("#informationForm").serialize();
        console.log("保存===="+JSON.stringify(data));
        $.ajax({
            cache: false,
            type: 'POST',
            url: "/information/updateInformation",
            dataType: "json",
            data: formData,
            async: false,
            success: function(data){
                if(data.result == "success"){
                    top.layer.alert("保存成功",{icon:1});
                    saveFlag = true;
                }else{
                    top.layer.alert("保存异常,请重试",{icon:0});
                }
            },
            error: function(){
                top.layer.alert("发生异常,请重试",{icon:2});
            }
        })

        delImgs(delImgsArr,filedir);

        if(!saveFlag) return false;
    });

    // 保存为草稿
    form.on("submit(addInformationToDraft)",function(data){
        form.render();
        if(isReUploadCoverFlag && !checkImgUpload()) return false;
        $("#inforStatus").val(0);
        $("#infoStatusValue").val("草稿");

        var formData = $("#informationForm").serialize();
        console.log("保存为草稿===="+JSON.stringify(data));
        $.ajax({
            cache: false,
            type: 'POST',
            url: "/information/updateInformation",
            dataType: "json",
            data: formData,
            async: false,
            success: function(data){
                if(data.result == "success"){
                    top.layer.alert("保存成功",{icon:1});
                    saveFlag = true;
                }else{
                    top.layer.alert("保存异常,请重试",{icon:0});
                }
            },
            error: function(){
                top.layer.alert("发生异常,请重试",{icon:2});
            }
        })

        delImgs(delImgsArr,filedir);
        if(!saveFlag) return false;
    });


    // 点击重新上传封面图()
    $("#reUploadCover").click(function (e) {
        e.preventDefault();
        e.stopPropagation();

        isReUploadCoverFlag = true;

        $("#coverImgs").hide("100",function(){
            $("#uploadCoverWrap").show("200");
        });

        // 删除已上传封面图
        var coverUrl = $("#coverUrl").val();
        var urlArr = coverUrl.split("@@@@");

        for(var i=0,len=urlArr.length;i<len;i++){
            var imgUrl = urlArr[i];
            var imgName = imgUrl.substring(imgUrl.indexOf(filedir),imgUrl.indexOf("?"));//information/20171017142014_psb.jpg
            delImgsArr.push(imgName);
        }
    })

    // 监听是否原创的单选按钮
    form.on('radio(fromType)', function(data){
        // data {"elem":{},"value":"1","othis":{"0":{"jQuery191047573129280968063":35},"length":1}}
        if(data){
            var $ori = $("#originalAuthor");
            var $reprint = $("#reprintAuthor");

            if(data.value == "0"){
                $ori.show();
                $reprint.hide();
                // 只能这样设置,如果还有隐藏域,thymeleaf会当做类似checkbox的多个值传入
                $("#reprintAuthor > input").val($ori.children("input").val());
            }else{
                $reprint.show();// 给这个input上直接绑定值
                $("#reprintAuthor > input").val("");
                $ori.hide();
            }
        }
    });

    initFroalaEditor();
    function initFroalaEditor() {
        $('#froalaEditor').on('editable.initialized', function (e, editor) {
            //editor.setHTML("");
            editor.setHTML($("#contentH").val());
        }).editable({
            inlineMode: false,
            theme: 'gray',
            //模版
            height: '300px', //高度
            maxHeight: "500px",
            alwaysBlank: true,
            language: "zh_cn",
            direction: "ltr",
            allowedImageTypes: ["jpeg", "jpg", "png", "gif"],
            autosave: true,
            autosaveInterval: 2500,
            //saveURL: 'hander/FroalaHandler.ashx',
            saveParams: {postId: "123"},
            spellcheck: true,
            plainPaste: true,
            imageButtons: ["floatImageLeft", "floatImageNone", "floatImageRight", "linkImage", "replaceImage", "removeImage"],
            imageUploadURL: '/oss/ossImgUpload?filedir='+filedir,
            //pastedImagesUploadURL: '/ossUpload4', // 粘贴上传
            //imageParams: { postId: "123" },
            //enableScript: false
        })

        // 相关事件初始化
        // 内容保存
        $('#froalaEditor').on('editable.contentChanged', function (e, editor) {
            //只存内容
            $("#contentH").val(editor.getHTML());

            // var $content = $("#froalaEditor").find("div[contenteditable='true']").clone();
            // $content.css({"border":"none","height":"100%"}).attr("contenteditable","false");
            // var contentDom = $content[0];
            // console.log(contentDom.outerHTML);
            // $("#contentH").val(contentDom.outerHTML);
        });

        // 图片删除
        $('#froalaEditor').on({
            'editable.beforeImageUpload': function(e, editor, $img) {
                var imgSize = $img[0].size;
                if(imgSize > 1024*200){
                    top.layer.alert("图片大小不能超过200kb",{icon:0});
                    return false;
                }
            },
            'editable.afterRemoveImage': function(e, editor, $img) {
                // Make delete image request.
                console.log ($img);
            },'editable.beforeRemoveImage': function (e, editor, $img) {
                // http://zhiyume-img.oss-cn-beijing.aliyuncs.com/information/20171017142014_psb.jpg?Expires=1823581214&OSSAccessKeyId=LTAI8hTtxsI962e5&Signature=11WpPsM4IoeGvt9YKW13VXBPEyg%3D

                // 点击保存的时候再统一删除,否则会造成数据库未删的情况
                var imgUrl = $($img).attr("src");
                var imgName = imgUrl.substring(imgUrl.indexOf(filedir),imgUrl.indexOf("?"));//information/20171017142014_psb.jpg

                delImgsArr.push(imgName);

                // console.log("********"+imgUrl+"********"+imgName);
                // var data = {"imgName":imgName,"filedir":filedir};
                // $.ajax({
                //     type: 'POST',
                //     url: "/oss/delPic",
                //     data: data,
                //     success: function(data){
                //         if(data["result"] == "success"){
                //             console.log("删除成功" + "============" + JSON.stringify(data));
                //         }else{
                //             console.log("删除失败" + "============" + JSON.stringify(data));
                //         }
                //     },
                //     error: function(){
                //         console.log("删除失败");
                //     }
                // });
            }
        })
    }


    var imgUrlArr = [];
    initCoverImgUpload();
    // 封面图上传初始化
    function initCoverImgUpload() {
        $.Tupload.init({
            url: '/oss/ossImgUpload?filedir='+filedir,
            title: "封面图大小不能超过300kb<span style='color:red;'>(*第一张将被作为封面)</span>",
            fileNum: 3, // 上传文件数量
            divId: "T_upload", // div  id
            accept: "image/jpeg,image/x-png,image/jpg", // 上传文件的类型
            fileSize:300,     // 上传文件的大小 kb
            filedir:filedir, // 图片上传至oss对应的目录
            onSuccess: function(data, i) {
                imgUrlArr[i] = data["link"];
                $("#coverUrl").val(imgUrlArr.join("@@@@"));
            },
            onDelete: function(i) {

            }
        });
    }

    // 封面图上传是否达3张
    function checkImgUpload(){
        if(imgUrlArr.length < 3){
            top.layer.alert("封面图必须上传三张",{icon:0});
            return false;
        }
        return true;
    }

    // 编辑部分信息初始化
    //initInfo();
    function initInfo(){
        // 内容
        // console.log(">>>>>>>>>>>>>>>"+$("#contentH").val());
        // $("#froalaEditor").val($("#contentH").val());
        // //$("#froalaEditor").text($("#contentH").val());
        // $("[contenteditable='true']").val("");
        // $("[contenteditable='true']").append($($("#contentH").val()));

        // 封面图
        // var coverUrl = $("#coverUrl").val();
        // var coverImgWrap = $("#coverImgWrap");
        // if(!coverUrl) coverImgWrap.html("暂无");
        //
        // var urls = coverUrl.split("@@@@");
        // var html = "";
        // for(var i=0,len=urls.length;i < len;i++){
        //     html += "<img class='cover-img' src='" + urls[i] + "'/>";
        // }
        // coverImgWrap.html(html);

    }

    function delImgs(imgUrlArr,filedir) {
        if(imgUrlArr.length < 1) return false;
        var data = {"imgUrlArr":imgUrlArr,"filedir":filedir};

        $.ajax({
            cache: false,
            type: 'POST',
            url: "/information/delImgs",
            dataType: "json",
            data: data,
            async: false,
            success: function(res){
                if(res.result == "success"){
                    console.log("---------删除成功---------");
                }else{
                    console.log("---------删除异常----------");
                }
            },
            error: function(){
                console.log("发生异常,请重试");
            }
        });
    }
})
